// 响叮当
<template>
  <div>
    <van-form class="jingle-cat">
      <van-field
        v-model="ruleForm.mobile"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
        @blur="onBlur('0')"
      />
      <van-field
        v-model="ruleForm.pwd"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
        @blur="onBlur('1')"
      />
      <div class="popup-open__form-code">
        <van-field
          v-model="ruleForm.captcha"
          type="tel"
          label="验证码"
          placeholder="请填写验证码"
          clearable
          @blur="onBlur('2')"
        />
        <van-image :src="imageSrc" @click="onGetCaptcha">
          <template v-slot:error>加载失败</template>
        </van-image>
      </div>
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-radio-group v-model="type" direction="horizontal">
            <van-radio
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.type"
              checked-color="#e4393c"
            >{{ option.label }}</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-cell-group>
        <van-cell class="van-cell__tip" v-for="(content, index) in returnContent" :key="index" :title="content" />
      </van-cell-group>
    </van-form>
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>
  </div>
</template>

<script>
import dayjs from "dayjs";
export default {
  name: "JingleCat",
  props: {
    index: {
      type: String,
      default: ''
    },
    item: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      ruleForm: {
        mobile: "18989866653",
        pwd: "Bb123456",
        captchaKey: "",
        captcha: ""
      },
      imageSrc: "",
      IntervalTime: 3,
      type: "0",
      typeOptions: [
        { label: "当日单", type: "0" },
        { label: "流量单", type: "2" }
      ],
      startFlag: false,
      accessToken: "",
      timer: null,
      taskId: "",
      returnContent: [],
      currentUrl: "https://api.qvmqfle.cn:8442/task/list_plan_worker"
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      this.iconItems =
        this.$store.getters.iconItems.length !== 0
          ? this.$store.getters.iconItems
          : this.$storage.get("resultIcon");
      this.iconItems[this.index].opened = this.startFlag ? '已启动' : '待启动';
      this.$store.commit("SET_ICONITEMS", this.iconItems);
      this.$storage.set("resultIcon", this.iconItems);
    },
    returnContent() {
      
      if (this.returnContent.length >= 10) {
        this.returnContent = this.returnContent.filter((item, i) => i < 5);
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 0) {
        this.onGetCaptcha();
      }
    }
  },
  methods: {
    // 失去焦点
    onBlur(index) {
      if (index === "0") {
        if (!/^1[3456789]\d{9}$/.test(this.ruleForm.mobile)) {
          this.$toast("手机号码输入有误");
          return false;
        }
      } else if (index === "1") {
        if (this.ruleForm.password === "") {
          this.$toast("密码输入有误");
          return false;
        }
      } else if (index === "2") {
        if (this.ruleForm.captcha === "") {
          this.$toast("验证码输入有误");
          return false;
        }
      }
    },
    // 获取UUID
    getUuid() {
      var len = 32; //  32长度
      var radix = 16; //  16进制
      var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split(
        ""
      );
      var uuid = [],
        i;
      radix = radix || chars.length;
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
      } else {
        var r;
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
        uuid[14] = "4";
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | (Math.random() * 16);
            uuid[i] = chars[i == 19 ? (r & 0x3) | 0x8 : r];
          }
        }
      }
      return uuid.join("");
    },
    // 获取验证码
    onGetCaptcha() {
      const _this = this;
      _this.imageSrc = "";
      _this.ruleForm.captchaKey = _this.getUuid();
      this.$ajax({
        url:
          "https://api.qvmqfle.cn:8442/captcha/gen_img?key=" +
          this.ruleForm.captchaKey,
        type: "get",
        ajaxData: {},
        method: () => {
          _this.imageSrc =
            "https://api.qvmqfle.cn:8442/captcha/gen_img?key=" +
            _this.ruleForm.captchaKey;
        }
      });
    },
    // 登录 => 接单
    onStart() {
      this.onLogin();
    },
    // 登录
    onLogin() {
      const _this = this;
      if (!this.startFlag) {
        if (!/^1[3456789]\d{9}$/.test(this.ruleForm.mobile)) {
          this.$toast("手机号码输入有误");
          return false;
        }
        if (this.ruleForm.pwd === "") {
          this.$toast("密码输入有误");
          return false;
        }
        if (this.ruleForm.captcha === "") {
          this.$toast("验证码输入有误");
          return false;
        }
        if (this.IntervalTime === "") {
          this.$toast("抢单间隔输入有误");
          return false;
        }
        this.accessToken = "";
         this.returnContent = [];
        this.startFlag = true;
        this.returnContent.unshift(
          dayjs().format("HH:mm:ss") + " " + "正在登录"
        );
        this.$ajax({
          url: "https://api.qvmqfle.cn:8442/auth/login_4_web",
          type: "post",
          ajaxData: {
            values: _this.ruleForm
          },
          method: res => {
            _this.returnContent.unshift(
              dayjs().format("HH:mm:ss") + " " + res.msg
            );
            if (res.code === 2000) {
              _this.startFlag = true;
              _this.accessToken = res.data.accessToken;
              _this.platform = res.data.platform;
              _this.userId = res.data.userId;
              _this.$storage.set("0", _this.accessToken);
              _this.onGetTaskList(_this);
            } else {
              _this.startFlag = false;
            }
          }
        });
      } else {
        this.returnContent.unshift(
          dayjs().format("HH:mm:ss") + " " + "接单取消"
        );
        this.$toast({
          message: "已停止接单",
          onClose: () => {
            clearInterval(_this.timer);
            _this.startFlag = false;
          }
        });
      }
    },
    // 任务列表
    onGetTaskList(_this) {
      clearInterval(_this.timer);
      _this.taskId = "";
      _this.$ajax({
        url: _this.currentUrl,
        type: "post",
        ajaxData: {
          values: {
            type: _this.type === 0 ? '' : 2,
            flowTypeFlag: _this.type === 0 ? _this.type : '',
            cancelFlag: 0
          }
        },
        headers: {
          "x-rn-access-token": _this.accessToken,
          "x-rn-platform": _this.platform,
          "x-rn-user-id": _this.userId
        },
        method: res => {
          _this.returnContent.unshift(
            dayjs().format("HH:mm:ss") + " " + res.msg
          );
          if (res.code === 2000) {
            // 接单
            _this.taskId = res.data.list[0].id;
            _this.onGetOrder(_this);
          } else if (res.code === 0) {
            // 暂无数据 => 循环请求
            _this.timer = setInterval(() => {
              if(_this.startFlag) {
              _this.onGetTaskList(_this);
              }
            }, _this.IntervalTime * 1000);
          } else {
            _this.startFlag = false;
          }
        }
      });
    },
    onGetOrder(_this) {
      _this.$ajax({
        url:
          _this.type === "0"
            ? "https://api.qvmqfle.cn:8442/task/accept_task"
            : "https://api.qvmqfle.cn:8442/task/accept_task_4_flow",
        type: "post",
        ajaxData: {
          values: {
            taskId: _this.taskId
          }
        },
        headers: {
          "x-rn-access-token": _this.accessToken,
          "x-rn-platform": _this.platform,
          "x-rn-user-id": _this.userId
        },
        method: res => {
          _this.returnContent.unshift(
            dayjs().format("HH:mm:ss") + " " + res.msg
          );
          _this.startFlag = false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.popup-open__form-code {
  width: 100%;
  @include flex($flexWrap: nowrap);
  .van-image {
    flex: 0 0 100px;
    height: 44px;
  }
}
</style>